from __future__ import division
import numpy as np
def aimFunction(x):
    y = (x-50)**2
    return y

def SA(T0,Tmin,k):
    #############
    #T0:初始温度
    #Tmin:最低温度
    #k:迭代次数
    #############
    T = T0
    #初始解
    x = np.random.uniform(low = 0, high = 100)
    #初始化结果
    y = aimFunction(x)
    t = 0
    while T > Tmin:
        for i in range(k):
            #计算目标函数
            y = aimFunction(x)
            #新解
            xNew = x + np.random.uniform(low = -0.055, high = 0.055)
            if 0 <= xNew and xNew <= 100:
                #计算目标函数
                yNew = aimFunction(xNew)
                if yNew < y:
                    x = xNew
                else:
                    p = np.exp( -(yNew - y)/T)
                    r = np.random.uniform(low = 0,high = 1)
                    if r < p:
                        x = xNew
                    else:
                        pass
        t += 1
        #退火函数
        T = T0/(1+t)
    print(x,aimFunction(x))
    return 

if __name__ == "__main__":
    SA(1000,1,100)
